package com.qinhailin.portal.dbm.ctrl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.qinhailin.common.base.BaseController;
import com.qinhailin.common.routes.ControllerBind;
import com.qinhailin.common.util.AESUtil;
import com.qinhailin.portal.dbm.model.CTCustomer;
import com.qinhailin.portal.dbm.model.DTQuery;
import com.qinhailin.portal.dbm.po.QueryText;
import com.qinhailin.portal.dbm.service.CTCustomerServiceImpl;
import com.qinhailin.portal.dbm.service.DTQueryServiceImpl;

/**
 * 联系人
 * @author ward
 */
@ControllerBind(path="/portal/dbm/querytext")
@Clear
public class QuerytextController extends BaseController{
	
	private static final Logger log = Logger.getLogger(QuerytextController.class);
	public static List<QueryText> querytexts = null;
	
	@Inject
	private CTCustomerServiceImpl customerService;
	@Inject
	private DTQueryServiceImpl queryService;
	
	public void index() {
		//DTCustomer c = this.getSessionAttr("customer");
		Integer rCustID = this.getInt();
		CTCustomer c = customerService.findByID(rCustID);
		// 并发的问题???
		if(c != null) {
			if(querytexts == null) {
				List<DTQuery> qts = queryService.list();
				List<QueryText> rs = new ArrayList<>();
				if(qts != null) {
					for(DTQuery q : qts) {
						if(q.getXIsOK() != null && q.getXIsOK().equals(1)) {
							rs.add(
									new QueryText()
										.setSID(q.getSID())
										.setXInterval(q.getXInterval())
										.setXName(q.getXName())
										.setXPath(q.getXPath())
										.setXText(q.getXText())
										.setXType(q.getXType())
										.setXIsPreSID(q.getXIsPreSID() != null && q.getXIsPreSID().equals(1))
										.setXIsPreTime(q.getXIsPreTime() != null && q.getXIsPreTime().equals(1))
										
									);
						}
					}
				}
				//querytexts = AESUtil.encrypt(JSONArray.toJSONString(rs), c.getStr("xKey"));
				querytexts = rs;
			}
			log.info("CLIENT CONNECTING... rCustID:" + c.getSID());
			this.renderJson(AESUtil.encrypt(JSONArray.toJSONString(querytexts), c.getStr("xKey")));
			return;
		}
		log.info("CLIENT CONNECTING FAILED, rCustID:null");
		this.renderNull();
	}
		

}
